from audioop import add

from django.contrib import admin
from django.utils.safestring import mark_safe
from django_apscheduler.models import DjangoJob

from .models import SchedulerJob
from .views import add_job, modify_job, pause_job, resume_job


@admin.register(SchedulerJob)
class SchedulerJobAdmin(admin.ModelAdmin):
    actions = ["start_job","pause_job"]

    # 修改列表显示的状态文字
    def status_buttons(self,obj):
        status = ""
        icon = ""
        if obj.status == 0:
            status = "停止"
            icon = "fa fa-stop-circle"
        elif obj.status == 1:
            status = "运行"
            icon = "fa fa-play-circle"
        elif obj.status == 2:
            status = "暂停"
            icon = "fa fa-pause-circle"
        html = '<span><i class="%s" ></i>%s</span>'  % (icon,status)
        return mark_safe(html)
    status_buttons.short_description = "状态"

    # 需要显示的字段信息
    list_display = ("name", "status_buttons", "begin_time")

    # 重载save方法,在保存数据时更新定时任务
    def save_model(self, request, obj, form, change) -> None:
        # 更新定时任务参数
        modify_job(str(obj.id),{"begin_time":str(obj.begin_time)})
        return super().save_model(request, obj, form, change)

    def start_job(self,request, queryset):
        for obj in queryset:
            # 查询job是否已存在,不存在则创建
            if DjangoJob.objects.filter(id=str(obj.id)).count() > 0:
                resume_job(str(obj.id))
            else:
                add_job("mars.apps.systems.services:backup_db",{"id":str(obj.id),"name":obj.name,"begin_time":str(obj.begin_time)})
            # 修改任务状态
            obj.status = 1
            obj.save()
    start_job.short_description = "启动"


    def pause_job(self,request, queryset):
        for obj in queryset:
            pause_job(str(obj.id))
            obj.status = 2
            obj.save()
    pause_job.short_description = "暂停"


    # 禁止新增、修改和删除功能
    def has_add_permission(self, request):
        """禁用增加按钮"""
        return False
    
    def  has_delete_permission(self, request, obj=None):
        """禁用删除按钮"""
        return False
    